﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraTab;
using System.Reflection;
using DevExpress.XtraEditors;
using System.IO;

namespace Lamex.mIE.ucControls
{


    public partial class ucShowPic_Ref : UserControl
    {
        int angle = 0;//旋转角度

        PictureBox pic = new PictureBox();
        XtraTabPage Page = new XtraTabPage();
        Bitmap myBmp;//图片定义
        Point mouseDownPoint = new Point(); //记录拖拽过程鼠标位置
        bool isMove = false;    //判断鼠标在picturebox上移动时，是否处于拖拽过程(鼠标左键是否按下)
        int zoomStep = 75;      //缩放步长
        private static Dictionary<string, XtraTabPage> TabPageDic = new Dictionary<string, XtraTabPage>();
        private static Dictionary<string, PictureBox> PictureDic = new Dictionary<string, PictureBox>();
        private static Dictionary<string, Bitmap> BitDic = new Dictionary<string, Bitmap>();
        private DevExpress.XtraTab.XtraTabControl xtraTabControl2 = new DevExpress.XtraTab.XtraTabControl();
        public ucShowPic_Ref()
        {
            InitializeComponent();
            this.xtraTabControl2.SelectedPageChanged += new DevExpress.XtraTab.TabPageChangedEventHandler(this.xtraTabControl2_SelectedPageChanged);
            xtraTabControl2.Dock = DockStyle.Fill;
            panelControl1.Controls.Add(xtraTabControl2);
        }

        #region 图纸缩放平移
        //鼠标按下功能
        private void pic_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
                isMove = true;
                pic.Focus();//
            }
        }
        //松开鼠标
        private void pic_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMove = false;
            }
        }
        //鼠标移动
        private void pic_MouseMove(object sender, MouseEventArgs e)
        {
            pic.Focus();//
            if (isMove)
            {
                int x, y;
                int moveX, moveY;
                moveX = Cursor.Position.X - mouseDownPoint.X;
                moveY = Cursor.Position.Y - mouseDownPoint.Y;
                x = pic.Location.X + moveX;
                y = pic.Location.Y + moveY;
                pic.Location = new Point(x, y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
            }
        }
        //鼠标滚轮滚动功能
        private void pic_MouseWheel(object sender, MouseEventArgs e)
        {
            int x = e.Location.X;
            int y = e.Location.Y;
            int ow = pic.Width;
            int oh = pic.Height;
            int VX, VY;
            if (e.Delta > 0)
            {
                pic.Width += zoomStep;
                pic.Height += zoomStep;

                PropertyInfo pInfo = pic.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
                    BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(pic, null);

                pic.Width = rect.Width;
                pic.Height = rect.Height;
            }
            if (e.Delta < 0)
            {

                if (pic.Width < myBmp.Width / 10)
                    return;

                pic.Width -= zoomStep;
                pic.Height -= zoomStep;
                PropertyInfo pInfo = pic.GetType().GetProperty("ImageRectangle", BindingFlags.Instance |
                    BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(pic, null);
                pic.Width = rect.Width;
                pic.Height = rect.Height;
            }

            VX = (int)((double)x * (ow - pic.Width) / ow);
            VY = (int)((double)y * (oh - pic.Height) / oh);
            pic.Location = new Point(pic.Location.X + VX, pic.Location.Y + VY);

        }
        private void Page_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
                isMove = true;
            }
        }

        private void Page_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMove = false;
            }
        }

        private void Page_MouseMove(object sender, MouseEventArgs e)
        {

            Page.Focus();
            if (isMove)
            {
                int x, y;
                int moveX, moveY;
                moveX = Cursor.Position.X - mouseDownPoint.X;
                moveY = Cursor.Position.Y - mouseDownPoint.Y;
                x = pic.Location.X + moveX;
                y = pic.Location.Y + moveY;
                pic.Location = new Point(x, y);
                mouseDownPoint.X = Cursor.Position.X;
                mouseDownPoint.Y = Cursor.Position.Y;
            }
        }
        #endregion

        #region 动态生成Tab页和图片
        /// <summary>
        /// 新增选项卡页
        /// </summary>
        /// <param name="tabControl">选项卡控件</param>
        /// <param name="tabPageName">当期选项卡页name名称</param>
        /// <param name="tabText">当前选项卡页Text标题</param>
        /// <param name="newFormName">当前选项卡中的新窗体</param>
        public void AddTabpage(XtraTabControl tabControl, string tabPageName, string tabText, string newFormName, string pictureName)
        {
            if (IsTabpageExsit(tabControl, tabPageName))
            {
                return;
            }
            Page = new XtraTabPage();
            Page.MouseDown += new System.Windows.Forms.MouseEventHandler(Page_MouseDown);
            Page.MouseUp += new System.Windows.Forms.MouseEventHandler(Page_MouseUp);
            Page.MouseMove += new System.Windows.Forms.MouseEventHandler(Page_MouseMove);
            Page.Name = tabPageName;
            Page.Text = tabText;
            Page.Tooltip = tabPageName;
            if (tabText.Contains("铝"))
                Page.Appearance.Header.BackColor = Color.DeepSkyBlue;
            else if (tabText.Contains("布"))
                Page.Appearance.Header.BackColor = Color.SkyBlue;
            else if (tabText.Contains("申"))
                Page.Appearance.Header.BackColor = Color.Blue; ;
            Page.Controls.Add(AddNewForm(newFormName, pictureName));
            tabControl.TabPages.Add(Page);
            TabPageDic.Add(tabPageName, Page);
            tabControl.SelectedTabPage = Page;


            if (Page == null)
                return;
            int length = xtraTabControl2.Height / 2;
            Button btn = new Button();
            Image clo = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\image\\left.ico");
            btn.Image = clo;
            btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            btn.BackColor = System.Drawing.Color.Transparent;
            btn.Name = "ClockwiseBtn";
            btn.Size = new Size(47, 36);
            btn.Location = new Point(5, length);
            Page.Controls.Add(btn);
            btn.Click += new EventHandler(aBtn_Click);

            Button btn2 = new Button();
            Image ant = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\image\\right.ico");
            btn2.Image = ant;
            btn2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            btn2.BackColor = System.Drawing.Color.Transparent;
            btn2.Name = "AntiClockwiseBtn";
            btn2.Size = new System.Drawing.Size(47, 36);
            btn2.Location = new System.Drawing.Point(5, length + 38);
            Page.Controls.Add(btn2);
            btn2.Click += new EventHandler(aBtn2_Click);

            //Page.Controls.Add(AddNewForm(newFormName));
        }
        /// <summary>
        /// 判断选项卡是否已经存在
        /// </summary>
        /// <param name="tabControl">选项卡控件</param>
        /// <param name="tabPageName">选项卡名称</param>
        /// <returns></returns>
        private bool IsTabpageExsit(XtraTabControl tabControl, string tabPageName)
        {
            foreach (var item in TabPageDic)
            {
                if (item.Key == tabPageName)
                {
                    tabControl.SelectedTabPage = item.Value;
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 在选项卡中生成图片
        /// </summary>
        /// <param name="form">图片名称</param>
        private PictureBox AddNewForm(string formName, string pictureName)
        {
            pic = new PictureBox();
            if (pictureName != "")
            {
                string filename = pictureName;
                byte[] buffer = Lamex.Common.DataConverter.ImgToByte(filename);
                myBmp = Lamex.Common.DataConverter.ByteToImg(buffer);
                // myBmp = new Bitmap(filename);
                pic.Name = formName;
                pic.Location = new System.Drawing.Point(110, 4);//5,4
                pic.Size = new System.Drawing.Size(580, 410);//100,50
                pic.TabIndex = 0;
                pic.TabStop = false;
                pic.Image = myBmp;
                pic.SizeMode = PictureBoxSizeMode.Zoom; //设置picturebox为缩放模式Zoom
                pic.MouseDown += new System.Windows.Forms.MouseEventHandler(pic_MouseDown);
                pic.MouseMove += new System.Windows.Forms.MouseEventHandler(pic_MouseMove);
                pic.MouseUp += new System.Windows.Forms.MouseEventHandler(pic_MouseUp);
                pic.MouseWheel += new MouseEventHandler(pic_MouseWheel);
                //pic.Width = 1033;//myBmp.Width;
                //pic.Height = 358;//myBmp.Height;
                PictureDic.Add(formName, pic);
                BitDic.Add(formName, myBmp);

            }
            return pic;
        }
        #endregion
        private void xtraTabControl2_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            XtraTabPage Page = xtraTabControl2.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDic)
            {

                if (item.Key == Page.Name)
                {
                    pic = PictureDic[item.Key];
                }
            }
            //pic.MouseDown += new System.Windows.Forms.MouseEventHandler(pic_MouseDown);
            //pic.MouseMove += new System.Windows.Forms.MouseEventHandler(pic_MouseMove);
            //pic.MouseUp += new System.Windows.Forms.MouseEventHandler(pic_MouseUp);
            //pic.MouseWheel += new MouseEventHandler(pic_MouseWheel);
            //Page.MouseDown += new System.Windows.Forms.MouseEventHandler(Page_MouseDown);
            //Page.MouseUp += new System.Windows.Forms.MouseEventHandler(Page_MouseUp);
            //Page.MouseMove += new System.Windows.Forms.MouseEventHandler(Page_MouseMove);

            #region 动态生成旋转按钮
            Page = xtraTabControl2.SelectedTabPage;

            #endregion
        }
        private void aBtn_Click(object sender, EventArgs e)
        {
            angle += 90;//每次增加90度
            XtraTabPage Page = xtraTabControl2.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDic)
            {
                if (item.Key == Page.Name)
                {
                    pic = PictureDic[item.Key];
                    foreach (var bmp in BitDic)
                    {
                        if (item.Key == Page.Name)
                        {
                            myBmp = BitDic[item.Key];
                            pic.Image = picRotate(myBmp, angle);//将旋转后的图片设置为picturebox背景
                            break;
                        }
                    }

                }
            }

            //顺时针旋转

            if (angle >= 360)
            {
                angle = 0;
            }

            GC.Collect();
        }
        private void aBtn2_Click(object sender, EventArgs e)
        {
            angle -= 90;//每次减少90度
            if (angle == 0)
            {
                angle = 360;
            }
            if (angle < 0)
            {
                angle = 270;
            }

            XtraTabPage Page = xtraTabControl2.SelectedTabPage;
            if (Page == null)
                return;
            foreach (var item in PictureDic)
            {
                if (item.Key == Page.Name)
                {
                    pic = PictureDic[item.Key];
                    foreach (var bmp in BitDic)
                    {
                        if (item.Key == Page.Name)
                        {
                            myBmp = BitDic[item.Key];
                            pic.Image = picRotate(myBmp, angle);//将旋转后的图片设置为picturebox背景
                            break;
                        }
                    }

                }
            }
            GC.Collect();
        }
        //使图片旋转的方法
        public static Bitmap picRotate(Bitmap b, int angle)
        {

            angle = angle % 360;            //弧度转换
            double radian = angle * Math.PI / 180.0;
            double cos = Math.Cos(radian);
            double sin = Math.Sin(radian);
            //原图的宽和高
            int w = b.Width;
            int h = b.Height;
            int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
            int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
            //目标位图
            // Image dsImage = new Bitmap(W, H);
            Bitmap dsImage = new Bitmap(W, H);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //计算偏移量
            Point Offset = new Point((W - w) / 2, (H - h) / 2);
            //构造图像显示区域：让图像的中心与窗口的中心点一致
            Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);
            Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
            g.TranslateTransform(center.X, center.Y);
            g.RotateTransform(360 - angle);
            //恢复图像在水平和垂直方向的平移
            g.TranslateTransform(-center.X, -center.Y);
            g.DrawImage(b, rect);
            //重至绘图的所有变换
            g.ResetTransform();
            g.Save();
            g.Dispose();
            //dsImage.Save("yuancd.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            // g.DrawImage(b, new Point(0, 0));
            return dsImage;
        }

        public void LoadImageList(List<string> AluminumImageList)
        {
            try
            {
                #region 清空控件值
                xtraTabControl2.TabPages.Clear();
                //int tabCount = this.xtraTabControl2.TabPages.Count();

                //for (int i = tabCount - 1; i >= 0; i--)
                //{

                //    this.xtraTabControl2.TabPages.RemoveAt(i);

                //}
                Page = new XtraTabPage();
                pic = new PictureBox();
                TabPageDic = new Dictionary<string, XtraTabPage>();
                PictureDic = new Dictionary<string, PictureBox>();
                BitDic = new Dictionary<string, Bitmap>();
                #endregion
                int autoName = 1;
                //int autoType = 1;
                //string lastName = "";
                //foreach (Model.B_IE_PathTypeInfo model in PathList)
                //{
                //    if (File.Exists(model.PathName))
                //    {
                //        if (model.TypeName != lastName)
                //            autoType = 1;
                //        AddTabpage(xtraTabControl2, autoName.ToString(), model.TypeName +"-"+ autoType,  autoName.ToString(), model.PathName);
                //        autoName++;
                //        autoType++;
                //        lastName = model.TypeName; ;

                //    }
                //}
                int ialumin = 1;
                foreach (string strPath in AluminumImageList)
                {
                    if (File.Exists(strPath))
                    {
                        AddTabpage(xtraTabControl2, autoName.ToString(), ialumin.ToString(), autoName.ToString(), strPath);
                        ialumin++;
                        autoName++;
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }
        public void SelectPageFocus(string PageName)
        {
            foreach (XtraTabPage page in xtraTabControl2.TabPages)
            {
                if (page.Text == PageName)
                {
                    xtraTabControl2.SelectedTabPage = page;//显示该页
                    return;
                }
            }
        }
    }
}
